﻿using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Metadata.SPI;
using T.FAS.Runtime.Metadata.Entity.MF;
using  T.ServiceFramework.ServiceGateway.Client;

namespace T.FAS.Runtime.MF.Plugin
{
    public class MFMetaDataManager : AbsMetaDataManager, IMetaDataManager
    {
        public IRefSchemaEntity BuildRefSchema(IMetaDataContent metaDataContent)
        {
            return null;
        }

        public IEnumerable<Metadata.Entity.Term> BuildTerms(IMetaDataContent metaDataContent, IEnumerable<Metadata.Entity.Term> terms = null)
        {
            return null;
        }

        public ValidateResult CompatibleValidate(IMetaDataContent metaData, IMetaDataContent oldMetaData)
        {
            return new ValidateResult()
            {
                state = "1"
            };
        }

        public MetaDataCompileResult Compile(IList<IMetaDataContent> metadatas)
        {
            return new MetaDataCompileResult();
        }

        public ConflictMessage ConflictCheck(List<IMetaDataContent> releasedMetaData, IMetaDataContent releaseingMetaData)
        {
            return new ConflictMessage();
        }

        public void Delete(IMetaDataContent metaData)
        {

        }

        public IMetaDataContent DeserializeObject(string metaDataString, MetadataSerializeType serializeType)
        {
            if (serializeType == MetadataSerializeType.JSON)
            {
                var microflowMeta = JsonConvert.DeserializeObject<MicroflowMeta>(metaDataString);
                return microflowMeta;
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        public IRefSchemaEntity DeserializeRefSchemaEntity(string schemaEntityJson)
        {
            return null;
        }

        public void Enable(params IMetaDataContent[] metaData)
        {

        }

        public IList<MetaDataExportContent> Export(params IMetaDataContent[] metaDataList)
        {
            return new List<MetaDataExportContent>();  
        }

        public override MetaGenerateCodeResult GenerateCode(IMetaDataContent metadata, bool isInternational)
        {
            return null;
        }

        public IMetaDataContent GetMetaDataContent(string metaDataId)
        {
            return null;
        }
        /// <summary>
        /// 获取依赖
        /// </summary>
        /// <param name="metaDataContent"></param>
        /// <returns></returns>
        public List<MetaDataDependency> GetMetaDataDependencys(IMetaDataContent metaDataContent)
        {
            MicroflowMeta microflowMeta = metaDataContent as MicroflowMeta;
            var dependencies = new List<MetaDataDependency>();
            if (microflowMeta.Dependencies == null)  return dependencies;

            foreach (var dependency in microflowMeta.Dependencies)
            {
                dependencies.Add(new MetaDataDependency { MetadataID= microflowMeta.ID, ParentMetadataID= dependency.MetaDataID, DependencyType = MetaDataDependencyType.Strong });
            }
            return dependencies;
        }
        /// <summary>
        /// 获取当前微流元数据变更
        /// </summary>
        /// <param name="oldMetaData"></param>
        /// <param name="newMetaData"></param>
        /// <returns></returns>
        public MetaDataUpdateSet GetMetaDataUpdateSet(IMetaDataContent oldMetaData, IMetaDataContent newMetaData)
        {
            MetaDataUpdateSet updateSet = new MetaDataUpdateSet()
            {
                UpdateItemList = new List<MetaDataUpdateItem>()
            };
            
            return updateSet;
        }
        public void Import(IList<MetaDataExportContent> contents, MetaDataImportStrategy importStrategy)
        {
            try
            {
                foreach (var exportContent in contents)
                {
                    var parameter = new Dictionary<string, string>();
                    if (importStrategy == MetaDataImportStrategy.Delete)
                    {
                        
                    }
                    else
                    {
                        var metaData = this.DeserializeObject(exportContent.Content, MetadataSerializeType.JSON);
                        MicroflowMeta microflowMeta = (MicroflowMeta)metaData;
                        if (microflowMeta != null)
                        {
                            if (importStrategy == MetaDataImportStrategy.Replace)
                            {
                                SGHttpClient httpClient2 = new SGHttpClient(true);
                                var mfParameter = new Dictionary<string, string>() {
                                    { "defJson",JsonConvert.SerializeObject(new List<object>(){ microflowMeta }) }
                                };
                                var response = httpClient2.PostCurrentIDC<object>("FASMF-PublishWorkflowForInternal", mfParameter, 60, 3);
                                if (response.state == "0")
                                {                                    
                                    throw new FasException(MicroflowExceptionCode.ImportFailed, $"发布流程定义失败,msg:{response.errmsg}");
                                }
                                    
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new FasException(MicroflowExceptionCode.ImportFailed, "导入Microflow元数据失败" + e.ToString());
            }
        }

        public void Release(IMetaDataContent metaData, ReleaseStrategy releaseStrategy)
        {

        }

        public void Save(IMetaDataContent metaData)
        {

        }

        public string SerializeObject(IMetaDataContent metadata, MetadataSerializeType serializeType)
        {
            if (serializeType == MetadataSerializeType.JSON)
            {
                var microflowMeta = metadata as MicroflowMeta;

                return JsonConvert.SerializeObject(microflowMeta, new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        public void Update(IMetaDataContent metaData)
        {

        }
        /// <summary>
        /// 依赖元数据有变更，需要修复
        /// </summary>
        /// <param name="metaDataContent"></param>
        /// <param name="updateSet"></param>
        /// <returns></returns>
        public MetaUpdateResult UpdateDependencyMetaData(IMetaDataContent metaDataContent, MetaDataUpdateSet updateSet)
        {
            return new MetaUpdateResult()
            {
                UpdateState = UpdateState.SuccessWithNoUpdate,
            };
        }        
        public ValidateResult Validate(IMetaDataContent metaData)
        {
            return new ValidateResult { state = "1" };
        }

    }
}